<template>
    <!-- 企业合同 -->
    <div class="firm ffffff flexbetween">
        <div class="l">
            <div style="height:2px;background-color: #F5F6F7;"></div>
            <div class="slider">
                <el-menu :default-active="archivedType" class="el-menu-vertical-demo" @select="handleOpen"
                    background-color="#fff" text-color="#333" active-text-color="#1063f1">
                    <el-menu-item index="0">
                        <i class="el-icon-eleme"></i>
                        <span slot="title">待归档合同</span>
                    </el-menu-item>
                    <el-menu-item index="1">
                        <div class="flexbetween">
                            <div class="flexleft">
                                <i class="el-icon-eleme"></i>
                                <span slot="title">已归档合同</span>
                            </div>
                            <i class="el-icon-plus" @click="dialogTypeVisible = true"></i>
                        </div>
                    </el-menu-item>
                </el-menu>
            </div>
            <div class="padding15 marignTop15">
                <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="filterText">
                </el-input>
            </div>
            <div class="padding15All">
                <el-tree :data="data" node-key="id" :props="defaultProps" ref="tree" :filter-node-method="filterNode"
                    default-expand-all @node-drop="handleDrop" @node-click="nodeclick" draggable :allow-drop="allowDroptree"
                    :allow-drag="allowDragtree">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <el-dropdown trigger="hover" @command="handleCommand($event, data)">
                            <span class="el-dropdown-link"><i class="el-icon-more el-icon--right"></i></span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="a">编辑</el-dropdown-item>
                                <el-dropdown-item command="b">删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </span>
                </el-tree>
            </div>
            <div class="padding15All flexcolumn" v-if="false">
                <p class="tabtext">暂无分类</p>
                <p class="tabtext">请联系管理员</p>
            </div>
        </div>
        <div class="r">
            <div style="height:2px;background-color: #F5F6F7;"></div>
            <div class="padding15All">
                <div class="padding15top flexbetween">
                    <div class="flexleft">
                        <p class="tabtext">已选择{{ multipleSelection.length }}条数据</p>
                        <!-- <el-button size="small" class="margin-left2">下载</el-button> -->
                        <el-button size="small" class="margin-left2" v-if="params.archivedType == 0"
                            @click="contractArchivedFn">归档</el-button>
                        <el-button size="small" class="margin-left2" v-if="params.archivedType == 1" @click="delContractFn">删除</el-button>
                    </div>
                    <el-button size="small" @click="dialogTableVisible = true">设置表头</el-button>
                </div>
                <div class="tableMain">
                    <el-table ref="multipleTable" :data="list" tooltip-effect="dark" style="width: 100%;height:100%;"
                        @selection-change="handleSelectionChange" :header-cell-style="tableHeaderColor">
                        <el-table-column fixed type="selection" width="50">
                        </el-table-column>
                        <div v-for="item in tablehead" :key="item.id">
                            <el-table-column :label="item.text" v-if="item.id == 7">
                                <template slot-scope="scope">
                                    <div class="tabtext" v-for="ite in scope.row.allSignContractName" :key="ite.userId">{{
                                        ite.userName }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column :prop="item.prop" :label="item.text" min-width="210" v-if="item.id != 7">
                            </el-table-column>
                        </div>
                        <el-table-column fixed="right" prop="m" label="操作" width="80">
                            <template slot-scope="scope">
                                <el-button @click="handleEdit(scope.row)" type="primary" size="small">查看</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="flexleft padding15All" style="justify-content: flex-end;">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="params.pageNo" :page-sizes="[10, 20, 50, 100]" :page-size="params.pageSize"
                        layout="total, prev, pager, next, sizes, jumper" :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
        <!-- 设置表头 -->
        <el-dialog title="" :visible.sync="dialogTableVisible" width="466px">
            <div class="padding15All textnone" style="border:2px solid #F5F6F7;">
                <div class="show">
                    <p class="tabtext">以下信息显示（拖动可调整排序、显示与否）：</p>
                    <ul class="flexleft" style="min-height: 50px;" @drop="drop($event, 'show')"
                        @dragover="allowDrop($event)">
                        <li v-for="(item, index) in tableheadbox" :key="index" draggable="true"
                            @dragstart="drag($event, item.id, 'show')">
                            {{ item.id }}.{{ item.text }}
                            <!-- <i class="el-icon-circle-close"></i> -->
                        </li>
                    </ul>
                </div>
                <div class="hide" id="hide">
                    <p class="tabtext">以下信息不显示：</p>
                    <ul class="flexleft" @drop="drop($event, 'hide')" @dragover="allowDrop($event)"
                        style="min-height: 30px;max-height: 150px;overflow-y: auto;">
                        <li v-for="(item) in tablebodybox" :key="item.id">
                            <div draggable="true"
                                @dragstart="drag($event, item.id, 'hide')">{{ item.text }}</div>
                        </li>
                    </ul>
                </div>
            </div>
            <span slot="footer" class="dialog-footer flexcenter">
                <el-button @click="dialogTableVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveloca()">保 存</el-button>
            </span>
        </el-dialog>
        <!-- 新增分类 -->
        <el-dialog title="分类名称" :visible.sync="dialogTypeVisible" width="400px">
            <div class="padding15All">
                <el-input type="text" placeholder="请输入内容" v-model="archivedTypeFn.typeName" maxlength="50" show-word-limit>
                </el-input>
            </div>
            <span slot="footer" class="dialog-footer flexcenter">
                <el-button @click="dialogTypeVisible = false">取 消</el-button>
                <el-button type="primary" @click="Addclass">确定</el-button>
            </span>
        </el-dialog>
        <!-- 归档 -->
        <el-dialog title="企业归档" :visible.sync="guidangshow" width="400px">
            <div class="padding15All">
                <el-cascader v-model="guidangid" :options="data" :props="casprops">
                    <template slot-scope="{ node, data }">
                        <span>{{ data.typeName }}</span>
                        <span v-if="!node.isLeaf"> ({{ data.subList.length }}) </span>
                    </template>
                </el-cascader>
                <!-- <el-input type="text" placeholder="请选择要归档的文件夹" v-model="archivedTypeFn.typeName" maxlength="50"
                    show-word-limit>
                </el-input> -->
            </div>
            <span slot="footer" class="dialog-footer flexcenter">
                <el-button @click="guidangshow = false">取 消</el-button>
                <el-button type="primary" @click="guidangevent">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { archivedEnterprise, addArchivedType, archivedTypeLevel, delArchivedType, contractArchived,delContract } from '@/api/firm'
import Cookies from 'js-cookie'//获取cookies的信息

export default {
    data() {
        return {
            guidangid:[],
            filterText: "",
            archivedTypeFn: {
                // enterpriseId:"",//企业id
                id: "",//当前分类id
                typeName: "",//分类名称
                parentId: "",//父级id
                userId: Cookies.get('admin_id'),//用户id//获取cookies中用户id的信息
            },
            dialogTableVisible: false,
            dialogTypeVisible: false,
            dom: '',
            domIndex: '',
            type: '',
            id: '',
            tablehead: [
                { text: "合同名称", id: 1, prop: "contractName" },
                { text: "合同编号", id: 2, prop: "contractNum" },
                { text: "合同状态", id: 3, prop: "signStateTxt" },
                { text: "合同完成时间", id: 4, prop: "signEndTime" },
                { text: "发起人", id: 5, prop: "launchContractName" },
                { text: "发起时间", id: 6, prop: "signTime" },
                { text: "签署人", id: 7, prop: "noSignContractName" }
            ],
            tablebody: [
                // { text: "已签署人", id: 7, prop: "hasSignContractName" },
                // { text: "未签署人", id: 8, prop: "noSignContractName" },
                { text: "抄送人", id: 9, prop: "contractName" },//
                { text: "合同文件名", id: 10, prop: "contractFileName" },
                { text: "附属文件名", id: 11, prop: "enclosureName" },
                { text: "更新时间", id: 12, prop: "updateTime" },
                // {text:"签订截止日期",id:13, prop: "signEndTime" },
                { text: "附属文件份数", id: 14, prop: "contractName" },//
                { text: "解决原因", id: 15, prop: "contractName" },//
                { text: "合同到期日", id: 16, prop: "signEndTime" },//
            ],
            tableheadbox: [
                { text: "合同名称", id: 1, prop: "contractName" },
                { text: "合同编号", id: 2, prop: "contractNum" },
                { text: "合同状态", id: 3, prop: "signStateTxt" },
                { text: "合同完成时间", id: 4, prop: "signEndTime" },
                { text: "发起人", id: 5, prop: "launchContractName" },
                { text: "发起时间", id: 6, prop: "signTime" },
                { text: "签署人", id: 7, prop: "noSignContractName" }
            ],
            tablebodybox: [
                // { text: "已签署人", id: 7, prop: "hasSignContractName" },
                // { text: "未签署人", id: 8, prop: "noSignContractName" },
                { text: "抄送人", id: 9, prop: "contractName" },//
                { text: "合同文件名", id: 10, prop: "contractFileName" },
                { text: "附属文件名", id: 11, prop: "enclosureName" },
                { text: "更新时间", id: 12, prop: "updateTime" },
                // {text:"签订截止日期",id:13, prop: "signEndTime" },
                { text: "附属文件份数", id: 14, prop: "contractName" },//
                { text: "解决原因", id: 15, prop: "contractName" },//
                { text: "合同到期日", id: 16, prop: "signEndTime" },//
            ],
            multipleSelection: [],
            emtypetxt: "",
            // 相对方个人请求参数
            archivedType: "0",
            params: {
                archivedType: "0",//是否归档 0 否 1 是
                archivedTypeId: "",//归档分类ID
                pageNo: 1,
                pageSize: 10
            },
            list: [],
            total: 0,

            data: [],
            defaultProps: {
                children: 'subList',
                label: 'typeName'
            },
            casprops: { 
                children: 'subList',
                value: "id", 
                label: "typeName" 
            },
            guidangshow:false
        }
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    mounted() {
        this.getList()
        this.getClass()
        let result = localStorage.getItem("filehead")
        let result2 = localStorage.getItem("filebody")
        if (result) {
            this.tablehead = JSON.parse(result)
            this.tablebody = JSON.parse(result2)
            this.tableheadbox = JSON.parse(result)
            this.tablebodybox = JSON.parse(result2)
        }
    },
    methods: {
        handleEdit(row) {
            console.log(row, "合同信息");
            this.$router.push({ path: "/SignDocument", query: { id: row.signContractId } },()=>{})
        },
        getList() {
            this.emtypetxt = '加载中...';
            archivedEnterprise(this.params).then(res => {
                this.list = res.result.records
                this.total = res.result.total
                if (this.list.length == 0) {
                    this.emtypetxt = '暂无数据'
                }
            }).catch(err => {
                console.log("请求失败", err)
            })
        },
        // 删除单个
        delevent(value, row) {
            this.$confirm('确定删除当前数据？', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                if (value == 1) {
                    this.delAll()
                } else {
                    this.delitem(row)
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 企业归档
        contractArchivedFn() {
            if (!this.multipleSelection.length) {
                this.$message.warning("请选择需要归档的内容");
                return false
            }
            this.guidangshow = true
        },
        // 企业归档删除
        delContractFn(){
            if (!this.multipleSelection.length) {
                this.$message.warning("请选择需要删除的内容");
                return false
            }
            let arr = []
            this.multipleSelection.forEach(item => {
                arr.push(item.signContractId)
            })
            let ids = arr.join()
            this.$confirm('确定删除当前数据？', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delContract({
                    contractId: ids
                }).then(res => {
                    if (res.code == 200) {
                        this.$message.success("删除成功");
                        this.getList()
                    } else {
                        this.$message.error(res.message);
                    }

                }).catch(err => {
                    this.$message.error(err.message);
                })
            })
            
            
        },
        guidangevent(){
            if (!this.guidangid.length) {
                this.$message.warning("请选择归档的文件夹");
                return false
            }
            this.guidangshow = false
            let arr = []
            this.multipleSelection.forEach(item=>{
                arr.push(item.signContractId)
            })
            contractArchived({
                contractId:arr.join(),
                archivedTypeId:this.guidangid[this.guidangid.length - 1]
            }).then(res=>{
               if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '归档成功!'
                    });
                    this.guidangid = []
                    this.getList()
                } else {
                    this.$message.error(res.message);
                }
            }).catch(err => {
                this.$message.error(err.message);
            })
        },
        // 分类列表
        getClass() {
            archivedTypeLevel().then(res => {
                this.data = res.result['0']
            }).catch(err => {
                this.$message.error(err.message);
            })
        },
        // 分类操作
        handleCommand(e, data) {
            if (e == "b") {
                delArchivedType({
                    archivedTypeId: data.id
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getClass()
                    } else {
                        this.$message.error(res.message);
                    }
                }).catch(err => {
                    this.$message.error(err.message);
                })
            } else {
                console.log(data, "999")
                this.archivedTypeFn = {
                    id: data.id,//当前分类id
                    typeName: data.typeName,//分类名称
                    parentId: data.parentId,//父级id
                    userId: Cookies.get('admin_id'),//用户id//获取cookies中用户id的信息
                }
                this.dialogTypeVisible = true
            }

        },

        handleDrop(draggingNode, dropNode, dropType, ev) {
            // draggingNode,被拖拽的节点
            // dropNode,结束拖拽的节点
            console.log('tree drop: ', draggingNode, dropNode);
            addArchivedType(
                {
                    id: draggingNode.data.id,//当前分类id
                    typeName: draggingNode.data.typeName,//分类名称
                    parentId: dropNode.data.id,//父级id
                    userId: Cookies.get('admin_id'),//用户id//获取cookies中用户id的信息
                }
            ).then(res => {
            }).catch(err => {
                this.$message.error(err.message);
            })
        },
        nodeclick(data,Node){
            console.log(data,"999")
            console.log(Node, "999")
            // this.archivedType = "1"
            this.archivedType = null
            this.params.archivedType = 1
            this.params.archivedTypeId = data.id
            this.params.pageNo = 1
            this.params.pageSize = 10
            this.getList()
            console.log(this.archivedType);
        },
        allowDroptree(draggingNode, dropNode, type) {
            return true;
        },
        allowDragtree(draggingNode) {
            return draggingNode.data.typeName.indexOf('1234') === -1;
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.typeName.indexOf(value) !== -1;
        },
        // 新增/编辑分类
        Addclass() {
            this.dialogTypeVisible = false
            addArchivedType(this.archivedTypeFn).then(res => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.getClass()
                } else {
                    this.$message.error(res.message);
                }
                this.archivedTypeFn.typeName = ""
            }).catch(err => {
                this.$message.error(err.message);
            })
        },
        tableHeaderColor({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === 0) {
                return 'background-color: #f7f8fa;color: #333;font-weight: 400;'
            }
        },
        // 拖拽
        drag(ev, id, type) {
            console.log("拖动", id);
            this.id = id;
            this.type = type
            if (type == 'show') {
                this.tableheadbox.forEach((item, index) => {
                    if (item.id == id) {
                        this.dom = item
                        this.domIndex = index
                    }
                })
            } else if (type == 'hide') {
                this.tablebodybox.forEach((item, index) => {
                    if (item.id == id) {
                        this.dom = item
                        this.domIndex = index
                    }
                })
            }
        },
        saveloca() {
            this.tablehead = JSON.parse(JSON.stringify(this.tableheadbox))
            this.tablebody = JSON.parse(JSON.stringify(this.tablebodybox))
            let result = JSON.stringify(this.tablehead)//表头
            let result2 = JSON.stringify(this.tablebody)//内容
            localStorage.setItem("filehead", result)
            localStorage.setItem("filebody", result2)
            this.dialogTableVisible = false
        },
        // 允许放下拖拽
        allowDrop(ev) {
            ev.preventDefault();
        },
        // 放下事件
        drop(ev, item) {
            ev.preventDefault();
            if (item == 'hide') {
                if (this.type == 'hide') {
                    return false
                }
                this.tablebodybox.push(this.dom)
                this.tableheadbox.splice(this.domIndex, 1);
            } else if (item == 'show') {
                if (this.type == 'show') {
                    return false
                }
                this.tableheadbox.push(this.dom)
                this.tablebodybox.splice(this.domIndex, 1);
            }
        },
        handleSizeChange(val) {
            this.params.pageSize = val
            this.getList()
        },
        handleCurrentChange(val) {
            this.params.pageNo = val
            this.getList()
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleNodeClick(data) {
            console.log(data);
        },
        handleOpen(key, keyPath) {
            console.log(key);
            this.archivedType = key
            this.params.archivedType = key
            this.params.archivedTypeId = ''
            this.getList()
        },
    }
}
</script>

<style lang='scss'>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>

<style lang="scss" scoped>
.firm {
    height: 100%;

    .l {
        height: 100%;
        min-width: 190px;
        box-sizing: border-box;
        border-right: 1px solid #e4e4e4;

        .nav-title {
            height: 50px;
            border-bottom: 1px solid #e4e4e4;
        }
    }

    .r {
        width: calc(100% - 190px);
        // flex-grow: 1;
        height: 100%;
        box-sizing: border-box;

        display: flex;
        flex-direction: column;
        position: relative;

        .pages {
            position: absolute;
            bottom: 0;
            right: 0;
        }
    }

    .show,
    .hide {
        .flexleft {
            flex-wrap: wrap;

            li {
                padding-left: 8px;
                padding-right: 8px;
                height: 24px;
                line-height: 22px;
                border-radius: 2px;
                border: 1px solid #b6caf2;
                margin-right: 8px;
                margin-bottom: 8px;
                cursor: pointer;
            }

        }
    }
}
</style>